package com.framework.common;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.framework.vo.IResult;
import com.framework.vo.Result;

/**
 * 
 * @Author: lbl 543414648@qq.com
 * @Date: 2015年6月10日 上午10:39:52
 */
public abstract class BaseServiceSupport<D, E, A extends BaseDao<D, E, PK>, PK extends java.io.Serializable> implements
		BaseService<D, E, PK> {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected abstract A getDao();

	@Override
	public IResult<Integer> countByExample(E example) {
		try {
			final int data = getDao().countByExample(example);
			return Result.createSuccess(data);
		} catch (Exception e) {
			logger.error("countByExample fail ", e);
			return Result.createFail();
		}
	}

	@Override
	public IResult<Integer> deleteByExample(E example) {
		try {
			final int data = getDao().deleteByExample(example);
			return Result.createSuccess(data);
		} catch (Exception e) {
			logger.error("deleteByExample fail ", e);
			return Result.createFail();
		}
	}

	@Override
	public IResult<Integer> save(D record) {
		try {
			final int data = getDao().insert(record);
			return Result.createSuccess(data);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("save fail ", e);
			return Result.createFail();
		}
	}

	@Override
	public IResult<Integer> saveSelective(D record) {
		try {
			final int data = getDao().insertSelective(record);
			return Result.createSuccess(data);
		} catch (Exception e) {
			logger.error("saveSelective fail ", e);
			return Result.createFail();
		}
	}

	@Override
	public IResult<Integer> saveOrUpdate(D record) {
		try {
			Serializable id = BeanUtils.getProperty(record, "id");
			if (id != null) {
				int result = getDao().updateByPrimaryKey(record);
				if (result > 0) {
					return Result.createSuccess(result);
				} else {
					return Result.createFail();
				}
			} else {
				return this.save(record);
			}

		} catch (Exception e) {
			logger.error("saveOrUpdate fail ", e);
			return Result.createFail();
		}

	}

	@Override
	public IResult<List<D>> findByExample(E example) {
		try {
			List<D> data = getDao().selectByExample(example);
			return Result.createSuccess(data);
		} catch (Exception e) {
			logger.error("findByExample fail ", e);
			return Result.createFail();
		}
	}

	@Override
	public IResult<List<D>> findAll() {
		try {
			List<D> data = getDao().selectByExample(null);
			return Result.createSuccess(data);
		} catch (Exception e) {
			logger.error("findAll fail ", e);
			return Result.createFail();
		}
	}

}
